# -*- encoding=utf-8 -*-

from  PIL import Image
import random
import time


def make_regalur_image(img, size=(256, 256)):
    """我们有必要把所有的图片都统一到特别的规格，在这里我选择是的256x256的分辨率。"""
    return img.resize(size).convert('RGB')

def hist_similar(lh, rh):
    assert len(lh) == len(rh)
    return sum(1 - (0 if l == r else float(abs(l - r))/max(l, r)) for l, r in zip(lh, rh))/len(lh)


def calc_similar(li, ri):
    return sum(hist_similar(l.histogram(), r.histogram()) for l, r in zip(split_image(li), split_image(ri))) / 16.0


def calc_similar_by_path(lf, rf):
    li, ri = make_regalur_image(Image.open(lf)), make_regalur_image(Image.open(rf))
    return calc_similar(li, ri)


def split_image(img, part_size = (64, 64)):
    w, h = img.size
    pw, ph = part_size
    assert w % pw == h % ph == 0
    return [img.crop((i, j, i+pw, j+ph)).copy() for i in range(0, w, pw) \
            for j in range(0, h, ph)]


# if __name__ == '__main__':
def get_test_list() ->list :
    print("FSCS过程:")
    all_image_num = 1113
    executed_size = 20
    candidate_size = 10
    tag = [0 for _ in range(0,all_image_num+1)]
    candidate = [0 for _ in range(0, candidate_size)]
    executed = [0 for _ in range(0, executed_size)]
    num = 0
    first_candidate = random.randint(1,all_image_num)
    print("No." + str(num+1) + "\t" + "图片编号：" + str(first_candidate))
    tag[first_candidate] = 1
    executed[num] = first_candidate
    num += 1
    start = time.time()
    for i in range(1, executed_size):
        for j in range(candidate_size):
            cur_random = random.randint(1,all_image_num)
            while tag[cur_random] == 1:
                cur_random = random.randint(1,all_image_num)
            candidate[j] = cur_random
        final, globe_similarty = 0, 2
        for j in range(candidate_size):
            local_similarity = 0
            for k in range(num):
                img1_path = '../image/test/test ('+ str(candidate[j]) +').jpg'
                img2_path = '../image/test/test ('+ str(executed[k]) +').jpg'
                cur_similarity = calc_similar_by_path(img1_path, img2_path)
                # print(cur_similarity)
                if(cur_similarity > local_similarity):
                    local_similarity = cur_similarity
            if(local_similarity < globe_similarty):
                final = candidate[j]
                globe_similarty = local_similarity
        print("No." + str(num+1) + "\t" + "图片编号：" + str(final) + "\t" + "与已选样本最大相似度：" + str(globe_similarty))
        executed[i] = final
        num += 1
    end = time.time()
    print("FSCS结果：", executed)
    print("用时："+str(end-start))
    return executed
    # img_num1, img_num2 = 21, 31
    # img1_path = './image/test/test ('+ str(img_num1) +').jpg'
    # img2_path = './image/test/test ('+ str(img_num2) +').jpg'
    # similary = calc_similar_by_path(img1_path, img2_path)
    # print("两张图片相似度为:%s" % similary)


